package com.jdpc.weparty.component

import com.jdpc.weparty.entity.Role
import com.jdpc.weparty.entity.User
import com.jdpc.weparty.repository.RoleRepository
import com.jdpc.weparty.service.udr.UdrService
import com.jdpc.weparty.service.user.UserService
import com.jdpc.weparty.service.user.generateUserInfo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextRefreshedEvent
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Component
import java.io.File
import java.util.*


@Component
class ApplicationStartUp : ApplicationListener<ContextRefreshedEvent> {
    @Value("\${jdpc.adminAccount}")
    private lateinit var adminUid: String

    @Value("\${jdpc.adminPwd}")
    private lateinit var adminPwd: String

    @Autowired
    private lateinit var serverConfig: ServerConfig

    override fun onApplicationEvent(contextRefreshedEvent: ContextRefreshedEvent) {
        val bannerDirections = "${serverConfig.localPath}${serverConfig.bannerPath}"
        val avatarDirections =  "${serverConfig.localPath}${serverConfig.avatarPath}"
        var direction = File(bannerDirections)
        if(!direction.exists()){
            direction.mkdirs()
        }
        direction = File(avatarDirections)
        if(!direction.exists()){
            direction.mkdirs()
        }
        val applicationContext = contextRefreshedEvent.applicationContext
        val roleRepository: RoleRepository = applicationContext.getBean(RoleRepository::class.java)
        for (i in 0..1) {
            val roleOptional: Optional<Role> = roleRepository.findById(i)
            if (!roleOptional.isPresent) {
                val role = Role()
                role.id = i
                when (i) {
                    0 -> role.name = Role.RoleType.ROLE_DEFAULT
                    1 -> role.name = Role.RoleType.ROLE_ADMIN
                }
                roleRepository.save(role)
            }
        }
        var admin: User
        val userService = applicationContext.getBean(UserService::class.java)
        val user = userService.getUser(1)
        if (user != null) {
            if (user.phoneNumber != adminUid || !BCryptPasswordEncoder().matches(adminPwd, user.password)) {
                admin = user.apply {
                    phoneNumber = adminUid
                    password = adminPwd
                }
                userService.changeInfo(admin.id, generateUserInfo(user))
                userService.resetPassword(admin.phoneNumber, admin.password)
            } else {
                admin = user
            }
        } else {
            admin = User().apply {
                phoneNumber = adminUid
                password = adminPwd
            }
            userService.register(generateUserInfo(admin), admin.password)?.apply {
                admin = this
            }

        }
        val udrService = applicationContext.getBean(UdrService::class.java)
        if (udrService.getRoles(admin.id).map {
                    it.name
                }.contains(Role.RoleType.ROLE_ADMIN).not()) {
            udrService.save(admin, Role.RoleLevel.ADMIN_LEVEL)
        }
    }

}